export default class WebSocketService {
    constructor(url, userInfo, tipMsg, noticeMsg, chatHistory) {
      this.url = url;
      this.userInfo = userInfo;
      this.tipMsg = tipMsg;
      this.noticeMsg = noticeMsg;
      this.chatHistory = chatHistory;
      this.ws = null;
      this.reconnectTimer = null;
    }
  
    connect() {
      this.ws = new WebSocket(this.url);
  
      this.ws.onopen = () => {
        this.tipMsg('success', '连接成功！');
        const sendData = {
          type: 1,
          name: this.userInfo.name,
          uid: this.userInfo.unicode,
        };
        this.ws.send(JSON.stringify(sendData));
      };
  
      this.ws.onmessage = (message) => {
        console.log('广播返回的消息', message);
        if (message.data instanceof Blob) {
          const reader = new FileReader();
          reader.onload = (e) => {
            const dataObj = JSON.parse(e.target.result);
            if (dataObj.type === 1) {
              this.noticeMsg('success', '通知', `${dataObj.name} 进入了聊天室~`);
            } else {
              this.chatHistory.push({
                userName: dataObj.name,
                uid: dataObj.uid,
                message: dataObj.message,
              });
            }
          };
          reader.readAsText(message.data);
        } else {
          const dataObj = JSON.parse(message.data);
          if (dataObj.type === 1) {
            this.noticeMsg('success', '通知', `${dataObj.name} 进入了聊天室~`);
          } else {
            this.chatHistory.push({
              userName: dataObj.name,
              uid: dataObj.uid,
              message: dataObj.message,
            });
          }
        }
      };
  
      this.ws.onclose = () => {
        this.tipMsg('error', '链接断开');
        // 断连 3 秒后重连
        this.reconnectTimer = setTimeout(() => {
          this.connect();
        }, 3000);
      };
  
      this.ws.onerror = () => {
        this.tipMsg('error', '连接失败');
        // 失败后重连
        this.reconnectTimer = setTimeout(() => {
          this.connect();
        }, 3000);
      };
    }
  
    close() {
      if (this.ws) {
        this.ws.close();
      }
      if (this.reconnectTimer) {
        clearTimeout(this.reconnectTimer);
      }
    }
  
    send(data) {
      if (this.ws && data.message.trim() && this.ws.readyState === WebSocket.OPEN) {
        this.ws.send(JSON.stringify(data));
      } else {
        return this.tipMsg("warning", "请先输入内容哦~");
      }
    }
  }